<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
      class="form-search"
    >
      <SearchTool
        :code="{
          workshop: 'productLine',
          line: 'productionLine',
          section: 'sectionCode',
        }"
        v-model:factory="queryParams.factory"
        v-model:workshop="queryParams.workshopCode"
        v-model:line="queryParams.productLine"
        v-model:section="queryParams.sectionCode"
      ></SearchTool>
      <el-form-item label="班组名称" prop="workGroupName">
        <el-input
          v-model="queryParams.workGroupName"
          placeholder="请输入班组名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['planning:planGroup:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['planning:planGroup:edit']"
          >编辑</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['planning:planGroup:remove']"
          >删除</el-button
        >
      </el-col> -->

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="班组编号"
        align="center"
        prop="workGroup"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{
            scope.row.workGroup
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column
        label="班组名称"
        align="center"
        prop="workGroupName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="工厂"
        align="center"
        prop="factoryName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="工段"
        align="center"
        prop="workshopName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="产线"
        align="center"
        prop="productLineName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="工艺段"
        align="center"
        prop="sectionName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="班长"
        align="center"
        prop="monitorName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['planning:planGroup:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['planning:planGroup:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" v-model="open" width="700px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="班组编号" prop="workGroup">
          <code-input
            v-model="form.workGroup"
            code="GROUP_CODE"
            :disabled="!!form.id"
            placeholder="请输入班组编号"
          />
        </el-form-item>
        <el-form-item label="班组名称" prop="workGroupName">
          <el-input v-model="form.workGroupName" placeholder="请输入班组名称" />
        </el-form-item>
        <SearchTool
          :code="{
            factory: 'factory',
            workshop: 'workshopCode',
            line: 'productLine',
            section: 'sectionCode',
          }"
          :itemStyle="{ width: '100%' }"
          v-model:factory="form.factory"
          v-model:workshop="form.workshopCode"
          v-model:line="form.productLine"
          v-model:section="form.sectionCode"
          @factoryChange="factoryChange"
          @workshopChange="workshopChange"
          @lineChange="lineChange"
          @sectionChange="sectionChange"
          :disabled="!!form.id"
        ></SearchTool>

        <el-form-item label="班长" prop="monitorName">
          <UserSelect
            v-model="form.monitorName"
            v-model:code="form.monitor"
            placeholder="请选择人员"
            title="选择人员"
          ></UserSelect>
        </el-form-item>
        <el-form-item label="班组成员" prop="shiftGroup">
          <el-form-item
            v-for="(el, index) in form.planGroupMemberList"
            :key="index"
            :label="el.workStationName"
            :prop="`planGroupMemberList.${index}.workStationStaffName`"
            :rules="[
              {
                required: true,
                message: '请选择人员',
                trigger: ['blur', 'change'],
              },
            ]"
            label-width="180px"
            style="width: 100%; margin-bottom: 18px"
            class="custom-label-left"
          >
            <UserSelect
              v-model="el.workStationStaffName"
              v-model:code="el.workStationStaff"
              :multiple="true"
              placeholder="请选择人员"
              title="选择人员"
            ></UserSelect>
          </el-form-item>
        </el-form-item>
        <!--        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            :disabled="!!form.id"
          ></el-input>
        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.custom-label-left .el-form-item__label {
  justify-content: flex-start;
}
</style>

<script setup name="Dict">
import {
  listShiftGroup,
  getShiftGroup,
  delShiftGroup,
  addShiftGroup,
  updateShiftGroup,
} from "@/api/base/plan/shiftMgt/shiftGroup";
import { listWorkStation } from "@/api/base/workstation";
import { getStation } from "@/api/base/processSection";
import DetailData from "./data";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const tableData = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const isEdit = ref(true);

const data = reactive({
  isEdit: false,
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storehouseCode: undefined,
    workGroupName: undefined,
    leaderName: undefined,
    status: undefined,
    factory: null,
    workshopCode: null,
    productLine: null,
    sectionCode: null,
  },
  rules: {
    workGroup: [
      {
        required: true,
        message: "请输入班组编号!",
        trigger: ["change", "blur"],
      },
    ],
    workGroupName: [
      {
        required: true,
        message: "请输入班组名称!",
        trigger: ["change", "blur"],
      },
    ],
    factory: [
      { required: true, message: "请选择工厂!", trigger: ["change", "blur"] },
    ],
    workshopCode: [
      { required: true, message: "请选择工段!", trigger: ["change", "blur"] },
    ],
    productLine: [
      { required: true, message: "请选择产线!", trigger: ["change", "blur"] },
    ],
    sectionCode: [
      { required: true, message: "请选择工艺段!", trigger: ["change", "blur"] },
    ],
    monitorName: [
      { required: true, message: "请输入班长!", trigger: ["change", "blur"] },
    ],
    status: [
      { required: true, message: "请输入状态!", trigger: ["change", "blur"] },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
function factoryChange(){
  form.value.planGroupMemberList = [];
}
function lineChange(){
  form.value.planGroupMemberList = [];
}
function workshopChange(){
  form.value.planGroupMemberList = [];
}
function sectionChange({ code }) {
  getStation({ sectionCode: code.deptCode }).then((res) => {
    const workStationList = res.rows;
    form.value.planGroupMemberList = [];
    workStationList.forEach((el) => {
      form.value.planGroupMemberList.push({
        workGroup: form.value.workGroup,
        workStationCode: el.stationCode,
        workStationName: el.stationName,
        workStationStaff: "",
        workStationStaffName: "",
      });
    });
  });
  // listWorkStation({ sectionCode: code }).then((res) => {
  //   const workStationList = res.rows;
  //   form.value.planGroupMemberList = [];
  //   workStationList.forEach((el) => {
  //     form.value.planGroupMemberList.push({
  //       workGroup: form.value.workGroup,
  //       workStationCode: el.workStationCode,
  //       workStationName: el.workStationName,
  //       workStationStaff: "",
  //       workStationStaffName: "",
  //     });
  //   });
  // });
}

/** 查询字典类型列表 */
function getList() {
  loading.value = true;
  listShiftGroup(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      response.rows.forEach((el) => {
        el.planGroupMember = el.planGroupMemberList;
      });
      tableData.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}

function handleDetail(row) {
  proxy.subPage(DetailData, { title: "班组详情", data: row });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    workGroup: "",
    workGroupName: "",
    factory: "",
    workshopCode: "",
    productLine: "",
    monitor: "",
    planGroupMemberList: [],
  };
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value.factory = null;
  queryParams.value.workshopCode = null;
  queryParams.value.productLine = null;
  queryParams.value.sectionCode = null;
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增班组";
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const dictId = row.id || ids.value;
  getShiftGroup(dictId).then((response) => {
    form.value = response.data;
    console.log("form.id:", form.value.id); // 添加这行代码
    open.value = true;
    title.value = "编辑班组信息";
    listWorkStation({ sectionCode: form.value.sectionCode }).then((res) => {
      if (
        form.value.planGroupMemberList &&
        form.value.planGroupMemberList.length
      ) {
        const workStationList = res.rows;
        for (let index = 0; index < workStationList.length; index++) {
          const el = workStationList[index];
          for (let i = 0; i < form.value.planGroupMemberList.length; i++) {
            const item = form.value.planGroupMemberList[i];
            if (el.workStationCode === item.workStationCode) {
              item.workStationName = el.workStationName;
              continue;
            }
          }
        }
      }
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if(!form.value.planGroupMemberList.length){
        proxy.$modal.msgError("所选工艺段下无岗位，请先添加岗位");
        return
      }
      if (form.value.id != undefined) {
        updateShiftGroup(form.value).then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        addShiftGroup(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const dictIds = row.id || ids.value;
  const workGroupCodes =
    row.workGroup ||
    ids.value
      .map((id) => tableData.value.find((item) => item.id === id)?.workGroup)
      .join(", ");

  proxy.$modal
    .confirm('是否确认删除班组编号为"' + workGroupCodes + '"的数据项？')
    .then(function () {
      return delShiftGroup(dictIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
